package com.wh.message.mail.utils;

import com.wh.common.util.Result;
import com.wh.msg.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import java.io.UnsupportedEncodingException;
import java.util.List;


public class MailUtil {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * spring 邮件发送对象
	 */
	private JavaMailSenderImpl javaMailSender;
	/**
	 *别名
	 */
	private String personal;

	// 设置utf-8或GBK编码，否则邮件会有乱码
	private MimeMessageHelper messageHelper = null;
	
	/**
	 * 邮件发送者别名
	 */
	public MailUtil(JavaMailSenderImpl javaMailSender){
		this.javaMailSender = javaMailSender;
	}
	public MailUtil(JavaMailSenderImpl javaMailSender, String personal){
		this.javaMailSender = javaMailSender;
		this.personal = personal;
	}

	public Result sendMail(SendMailMessage msg) {
		Result res ;
		logger.info("获取需要发送的消息："+msg.toString());
		//使用JavaMail的MimeMessage，支付更加复杂的邮件格式和内容
		MimeMessage mailMessage = javaMailSender.createMimeMessage();
		res = getMimeMessageHelper(msg, mailMessage);
		logger.info("调用发送信息："+res,mailMessage);
		if (ResultCode.RES_OK.equals(res.getResCode())) {
			MimeMessageHelper mail = (MimeMessageHelper) res.getResult();
			try {
                //发送文本并指定类型是否是HTML
				mail.setText(msg.getText(), msg.isHtml());
				List<FileUtil> files = msg.getListFile();
				if (null != files && files.size() > 0) {
					for (FileUtil fileUtil : files) {
						// 这里的方法调用和插入图片是不同的，使用MimeUtility.encodeWord()来解决附件名称的中文问题
						String fileName = fileUtil.getFileName();
                        byte [] bytes =fileUtil.getFileData();
						try {
							try {
								fileName = MimeUtility.encodeText(fileUtil.getFileName());
							}catch (UnsupportedEncodingException ex){
								ex.printStackTrace();
								logger.error("sendMail【1】发送邮件sendMail出现异常，ex={}",ex.getMessage());
								res.setResCode(ResultCode.RES_ERR);
								return res;
							}
                            ByteArrayDataSource bas = new ByteArrayDataSource(bytes,"application/octet-stream");
                            mail.addAttachment(fileName,bas);
						} catch (MessagingException e) {
							e.printStackTrace();
							res.setResCode(ResultCode.RES_ERR);
							logger.error("sendMail【2】发送邮件sendMail出现异常，上传附件错误e={}",e.getMessage());
							return res;
						}
					}
				}
				try {
					javaMailSender.send(mailMessage);
				} catch (MailException e) {
					logger.error("sendMail【3】发送邮件sendMail出现异常，发送失败e={}",e.getMessage());
					e.printStackTrace();
					res.setResCode(ResultCode.RES_ERR);
					res.setResult(e.getMessage());
					return res;
				}
			} catch (MessagingException e) {
				logger.error("sendMail【4】发送邮件sendMail出现异常，发送失败e={}",e.getMessage());
				e.printStackTrace();
				res.setResCode(ResultCode.RES_ERR);
				res.setResult(e.getMessage());
				return res;
			}
		}
		return res;
	}
	
	public Result getMimeMessageHelper(SendMailMessage msg,
			MimeMessage mailMessage) {
		Result res = new Result();

		try {
			messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
			if (null != msg.getTo() && msg.getTo().length > 0) {
				messageHelper.setTo(msg.getTo());// 接受者
			} else {
				res.setResCode(ResultCode.RES_5007);
				return res;
			}
            //抄送
			if (null != msg.getCc()) {
				messageHelper.setCc(msg.getCc());
			}
            //密送
			if (null != msg.getBcc()) {
				messageHelper.setBcc(msg.getBcc());
			}
			if (null != personal && !"".equals(personal)) {
				try {

                    //使用辅助类MimeMessage设定参数
					messageHelper.setFrom(javaMailSender.getUsername(),
							personal);// 发送者,这里还可以另起Email别名，不用和xml里的username一致
				} catch (UnsupportedEncodingException e) {
					logger.error("getMimeMessageHelper【1】发送邮件getMimeMessageHelper出现异常，别名错误e={}",e.getMessage());
					e.printStackTrace();
					res.setResCode(ResultCode.RES_ERR);
					res.setResult(e.getMessage());
					return res;
				}
			} else {
				messageHelper.setFrom(javaMailSender.getUsername());// 发送者
			}
			if (null != msg.getSubject() && !"".equals(msg.getSubject())) {
				messageHelper.setSubject(msg.getSubject());// 主题
			} else {
				res.setResCode(ResultCode.RES_5008);
				return res;
			}
			res.setResCode(ResultCode.RES_OK);
		} catch (MessagingException e) {
			logger.error("getMimeMessageHelper【2】发送邮件getMimeMessageHelper出现异常，邮件设置错误e={}",e.getMessage());
			e.printStackTrace();
			res.setResCode(ResultCode.RES_ERR);
			res.setResult(e.getMessage());
			return res;
		}
		res.setResult(messageHelper);
		return res;
	}


	public JavaMailSenderImpl getJavaMailSender() {
		return javaMailSender;
	}


	public void setJavaMailSender(JavaMailSenderImpl javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

}
